package com.txw.javaCore.server.mq;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.txw.javaCore.model.request.UserLoginRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * @PROJECT_NAME: JavaCoreB2
 * @DESCRIPTION: 系统日志记录（生产者）
 * @Author: 涂玄武
 * @DATE: 2021/2/22 17:10
 */
@Component
public class LogPublisher {

    private static final Logger log = LoggerFactory.getLogger(LogPublisher.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private Environment env;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 发送登录成功后的用户相关信息入队列
     * @param request
     */
    public void sendLogMsg(UserLoginRequest request){
        try {
            //设置消息传输格式为JSON
            rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
            //设置交换机
            rabbitTemplate.setExchange(env.getProperty("mq.login.exchange.name"));
            //设置路由
            rabbitTemplate.setRoutingKey(env.getProperty("mq.login.routing.key.name"));
            //发送消息
            rabbitTemplate.convertAndSend(request, message -> {
                //获取消息属性
                MessageProperties messageProperties = message.getMessageProperties();
                //设置消息的持久化模式为持久化
                messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                //设置消息头，表示传输的消息直接指定为某个类实例，消费者在监听消费时可以直接定义该类对象参数进行接收即可
                messageProperties.setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME,UserLoginRequest.class);
                //返回消息实例
                return message;
            });
            //输出日志信息
            log.info("系统日志记录-生产者-发送登录成功后的用户相关信息入队列-内容：{}",request);
        } catch (Exception e){
            log.error("系统日志记录-生产者-发送登录成功后的用户相关信息入队列-发生异常：{}",request,e.fillInStackTrace());
        }
    }
}
